// src/hooks/useWebSocket.ts
"use client"

import { useEffect, useState } from "react"

export function useWebSocket(wsUrl: string) {
  const [videoSrc, setVideoSrc] = useState<string | null>(null)
  const [networkError, setNetworkError] = useState(false)

  useEffect(() => {
    if (!wsUrl) {
      console.warn("WebSocket URL is empty. Skipping WebSocket initialization.")
      return
    }

    if (typeof window === "undefined") return

    console.log("Connecting to WebSocket:", wsUrl)
    const ws = new WebSocket(wsUrl)
    ws.binaryType = "blob"

    ws.onopen = () => {
      console.log("WebSocket 连接成功")
      setNetworkError(false)
    }

    ws.onmessage = (event) => {
      const blob = event.data as Blob
      const url = URL.createObjectURL(blob)
      setVideoSrc(url)
    }

    ws.onerror = (error) => {
      console.error("WebSocket 错误", error)
      setNetworkError(true)
    }

    ws.onclose = () => {
      console.log("WebSocket 已关闭")
      setNetworkError(true)
    }

    return () => {
      ws.close()
    }
  }, [wsUrl])

  return { videoSrc, networkError }
}